#!/usr/bin/env zsh

ACCOUNT="${1}"
page=1

[ -z "${2}" ] && save_dir="${HOME}/.igdl3/${ACCOUNT}" || save_dir="${2}/.igdl3/${ACCOUNT}" 

__err_parse_id() {
    echo "[ERR.] Could not parse ID."
    exit
}

__r_fname() {
    LC_CTYPE=C 
    
    tr -dc '[:alnum:]' < /dev/urandom \
        | head -c 8
}

parse_json_imgs() {
    jq -r '[.items][][] | [.src]' | jq -r '.[]'
}

get_id() {
    _user_id=$(\
               wget https://imginn.com/$ACCOUNT -qO- \
                   | grep -Eo '"[0-9]{5,}"' \
                   | head -n 1 \
                   | tr -dc '0-9')
    
    [ -z "${_user_id}" ] && __err_parse_id || echo "[${ACCOUNT}] Got user ID"
    
    mkdir -p "${save_dir}"
}

get_next_page() {
    page="${1}"
    _cursor=$(\
              wget "https://imginn.com/api/posts/?id=$_user_id&cursor=$_cursor" -qO- \
                  | jq -r '.cursor')
}

get_posts() {
    wget "https://imginn.com/api/posts/?id=$_user_id&cursor=$_cursor" -qO-
}

rename_media() {
    _jpg_media=($(find "${save_dir}" -iname "*.jpg*" -maxdepth 1))
    _mp4_media=($(find "${save_dir}" -iname "*.mp4*" -maxdepth 1))

    echo "[${ACCOUNT}] Sorting images"
    for (( i=1 ; i<=${#_jpg_media[@]} ; i++ )); do
        mv "${_jpg_media[${i}]}" "${save_dir}/$(__r_fname).jpg"
    done
        
    echo "[${ACCOUNT}] Sorting movies"
    for (( i=1 ; i<=${#_mp4_media[@]} ; i++ )); do
        mv "${_mp4_media[${i}]}" "${save_dir}/$(__r_fname).mp4"
    done
}

echo "[${ACCOUNT}] Getting user ID"
get_id "${1}"

while true; do
    img_page_array=($(get_posts | parse_json_imgs))
    echo "[${ACCOUNT}] Downloading page: ${page}"
    tr ' ' '\n' <<< "${img_page_array[*]}" | aria2c -d "${save_dir}" -q -s 10 -i - 
    
    get_next_page "${page}"
    ((page++))
    [[ "${_cursor}" == "null" ]] && break
done

#rename_media

echo "[${ACCOUNT}] Complete"
